<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类名" prop="categoryName">
        <el-input v-model="queryParams.categoryName" placeholder="请输入分类名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in campus_category_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['campus:category:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-if="refreshTable" v-loading="loading" :data="categoryList" row-key="categoryId"
      :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column label="分类名" prop="categoryName" />
      <el-table-column prop="icon" label="图标" align="center" width="100">
        <template #default="scope">
          <svg-icon :icon-class="scope.row.icon" style="width: 36px; height: 36px;" />
        </template>
      </el-table-column>
      <el-table-column label="缩略名" align="center" prop="slug" />
      <el-table-column label="排序" align="center" prop="orderNum" />
      <el-table-column label="系统内置" align="center" prop="type">
        <template #default="scope">
          <el-tooltip v-if="scope.row.type == 'Y'" content="系统内容不可删除，不可修改ID，不可发布墙，只用于前台展示，代码逻辑处理获取墙内容" placement="top">
            <el-badge is-dot class="item">
              <dict-tag :options="sys_yes_no" :value="scope.row.type" />
            </el-badge>
          </el-tooltip>
          <dict-tag v-else :options="sys_yes_no" :value="scope.row.type" />
        </template>
      </el-table-column>

      <el-table-column label="描述" align="center" prop="description" show-overflow-tooltip />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="campus_category_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['campus:category:edit']">修改</el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)"
            v-hasPermi="['campus:category:add']">新增</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['campus:category:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改分类管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="categoryRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级分类" prop="parentId">
          <el-tree-select v-model="form.parentId" :data="categoryOptions" :render-after-expand="false" check-strictly
            style="width: 240px" />
        </el-form-item>
        <el-form-item label="分类名" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名" />
        </el-form-item>

        <el-form-item label="菜单图标" prop="icon">
          <el-popover placement="bottom-start" :width="540" trigger="click">
            <template #reference>
              <el-input v-model="form.icon" placeholder="点击选择图标" @blur="showSelectIcon" readonly>
                <template #prefix>
                  <svg-icon v-if="form.icon" :icon-class="form.icon" class="el-input__icon"
                    style="height: 32px;width: 16px;" />
                  <el-icon v-else style="height: 32px;width: 16px;">
                    <search />
                  </el-icon>
                </template>
              </el-input>
            </template>
            <icon-select ref="iconSelectRef" @selected="selected" :active-icon="form.icon" />
          </el-popover>
        </el-form-item>

        <el-form-item label="缩略名" prop="slug">
          <el-input v-model="form.slug" placeholder="请输入缩略名" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入显示顺序" />
        </el-form-item>
        <el-form-item label="系统内置" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio v-for="dict in sys_yes_no" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" clearable>
            <el-option v-for="dict in campus_category_status" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Category">
import { listCategory, getCategory, delCategory, addCategory, updateCategory } from "@/api/campus/category";
import IconSelect from "@/components/IconSelect";
import { loadAllParams } from "@/api/page";
import { loadCategoryOptions } from "../../../api/campus/campus"

const { proxy } = getCurrentInstance();
const { campus_category_status, sys_yes_no } = proxy.useDict('campus_category_status', 'sys_yes_no');

const categoryList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(true);
const refreshTable = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    categoryName: null,
    parentId: null,
    slug: null,
    description: null,
    type: null,
    status: null,
  },
  rules: {
    categoryName: [
      { required: true, message: "分类名不能为空", trigger: "blur" }
    ],
    slug: [
      { required: true, message: "缩略名不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询分类管理列表 */
function getList() {
  loading.value = true;
  listCategory(queryParams.value).then(response => {
    categoryList.value = proxy.handleTree(response.data, "categoryId", "parentId");
    loading.value = false;
  });
}

/** 展示下拉图标 */
function showSelectIcon() {
  iconSelectRef.value.reset();
}
/** 图标选择 */
function selected(name) {
  form.value.icon = name;
}

/** 查询下拉树结构类别信息 */
const categoryOptions = ref([]);
const getCategoryOptions = async () => {
  try {
    const category = { value: 0, label: '主类目', children: [] };
    category.children = await loadCategoryOptions(loadAllParams);
    categoryOptions.value = [category];
  } catch (error) {
    console.error('加载分类数据失败:', error);
  }
}


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    categoryId: null,
    categoryName: null,
    parentId: null,
    orderNum: null,
    slug: null,
    description: null,
    type: null,
    icon: null,
    status: null,
    delFlag: null,
    createTime: null,
    createUser: null,
    updateTime: null,
    updateUser: null
  };
  proxy.resetForm("categoryRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  getCategoryOptions();
  if (row != null && row.categoryId) {
    form.value.parentId = row.categoryId;
  } else {
    form.value.parentId = 0;
  }
  open.value = true;
  title.value = "添加分类管理";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getCategoryOptions();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  getCategory(row.categoryId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改分类管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["categoryRef"].validate(valid => {
    if (valid) {
      if (form.value.categoryId != null) {
        updateCategory(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCategory(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除分类管理编号为"' + row.categoryId + '"的数据项？').then(function () {
    return delCategory(row.categoryId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

getList();
</script>
